package cn.itcast.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @author 虎哥
 */
@Component
public class LoginFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取Request
        HttpServletRequest request = ctx.getRequest();

        // 获取请求参数中的 access-token
        String token = request.getParameter("access-token");
        // 判断值是否为空
        if(StringUtils.isBlank(token)) {
            // 为空：拦截
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401); // 用户未登录，unauthorize 未授权
        }
        // 不为空：放行
        return null;
    }
}
